package com.invengo.testrfid.mvp.presenter;

import android.app.Application;

import com.invengo.testrfid.app.dao.QueryManager;
import com.invengo.testrfid.app.dao.RfidCageBind;
import com.invengo.testrfid.app.utils.Constant;
import com.invengo.testrfid.app.utils.MyCalback;
import com.invengo.testrfid.app.utils.MyLogUtils;
import com.invengo.testrfid.app.utils.ShareSaveUtils;
import com.invengo.testrfid.app.utils.TimeUtilsNew;
import com.invengo.testrfid.app.utils.UUIDUtils;
import com.invengo.testrfid.app.utils.WebServiceUtils;
import com.invengo.testrfid.app.utils.WifeStatueUtils;
import com.invengo.testrfid.mvp.contract.IndexContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;

import java.util.UUID;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;


@ActivityScope
public class IndexPresenter extends BasePresenter<IndexContract.Model, IndexContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private QueryManager queryManager;
    private int x = 0;

    private int uploadSuccessCount = 0;
    private int uploadFailedCount = 0;

    @Inject
    public IndexPresenter(IndexContract.Model model, IndexContract.View rootView) {
        super(model, rootView);
        this.queryManager = QueryManager.getManager();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.queryManager = null;
    }

    public void initExportCount() {

        long rfidCageBinds = queryManager.getRfidCageQuery().queryDataNoBindSize();
        mRootView.neddExport(rfidCageBinds);
    }

    public void generateDta() {

        mRootView.showLoading();
        final long begin = System.currentTimeMillis();

        Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final @NonNull ObservableEmitter<String> e) throws Exception {

                for (int i = 0; i < 2000; i++) {


                    RfidCageBind rfidCageBindNew = new RfidCageBind();
                    rfidCageBindNew.setId(UUIDUtils.getShortUUId());
                    rfidCageBindNew.setTagId("Tid1" + UUIDUtils.getShortUUId() +
                            Constant.ValueOfSpare + "Tid2" + UUIDUtils.getShortUUId());
                    rfidCageBindNew.setCageId("CageID" + UUIDUtils.getShortUUId());
                    rfidCageBindNew.setIsBind(false);
                    rfidCageBindNew.setBindTime(TimeUtilsNew.getStringTimelByLong(System.currentTimeMillis()));
                    rfidCageBindNew.setFailedMessage("");
                    queryManager.getRfidCageQuery().insert(rfidCageBindNew);
                }
                e.onNext("ok");
            }
        }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread());

        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(@NonNull String s) throws Exception {

                long during = System.currentTimeMillis() - begin;
                mRootView.showMessage(during + "ms");
                mRootView.hideLoading();
            }
        });


    }

    private long beginUpload ;

    public void uploadCageData() {

        beginUpload = System.currentTimeMillis();
        if (WifeStatueUtils.isNetworkAvailable(mApplication)) {
            mRootView.showLoading();
            skip = 0;
            uploadData();
        } else {
            mRootView.showMessage("网络未连接");
        }
    }

    private int skip = 0;

    private void uploadData() {

        int next = ShareSaveUtils.getIntFromTable("next");
        RfidCageBind rfidCageBind;
        if (next == 101) {
            rfidCageBind = queryManager.getRfidCageQuery().queryDataNoBind(skip);
        } else {
            rfidCageBind = queryManager.getRfidCageQuery().queryDataNoBind2(skip);
        }

        if (rfidCageBind != null) {

            String[] split = rfidCageBind.getTagId().split(Constant.ValueOfSpare);
            long time = TimeUtilsNew.getLongFromStrinig("20" + rfidCageBind.getBindTime().
                    trim() + ":00", "yyyy/MM/ddHH:mm:ss");
            String objectTime = TimeUtilsNew.getTimebyLong(time, "yyyy/MM/dd HH:mm:ss");
            uploadDataExcutor(rfidCageBind, rfidCageBind.getCageId(), split[0], split[1], objectTime);
        } else {

            ShareSaveUtils.saveIntInTable("next", 101);
            mRootView.showMessage("数据上传完成  " + uploadSuccessCount + "成功  " + uploadFailedCount + "失败");
            uploadFailedCount = 0;
            uploadSuccessCount = 0;
            initExportCount();
            mRootView.hideLoading();
            long during = System.currentTimeMillis() - beginUpload;
            MyLogUtils.log("init",during+"during",5);
        }
    }

    private void uploadDataExcutor(final RfidCageBind rfidCageBind, final String cageNo,
                                   final String rfid1, final String rfid2, final String time) {

        Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final @NonNull ObservableEmitter<String> e) throws Exception {

                WebServiceUtils.zs(cageNo, rfid1, rfid2, time, new MyCalback() {

                    @Override
                    public void onSuccesss(Object object) {
                        super.onSuccesss(object);

                        MyLogUtils.log("tag", "success", 1);
                        rfidCageBind.setIsBind(true);
                        queryManager.getRfidCageQuery().update(rfidCageBind);
                        uploadSuccessCount++;
                        e.onNext("success");
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);

                        MyLogUtils.log("tag", "err_upload_" + msg, 1);
                        skip++;
                        rfidCageBind.setFailedMessage(msg);
                        rfidCageBind.setIsBind(false);
                        queryManager.getRfidCageQuery().update(rfidCageBind);
                        uploadFailedCount++;
                        e.onNext("err");
                    }
                });

            }
        }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread());

        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(@NonNull String s) throws Exception {

                uploadData();
            }
        });
    }


}
